package com.example.peibei.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dingtao.common.bean.PayBanlance;
import com.dingtao.common.bean.PayOrder;
import com.dingtao.common.bean.PayPower;
import com.dingtao.common.bean.PayResult;
import com.dingtao.common.bean.SubmitOrder;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.DateUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.dingtao.common.util.recyclerview.SpacingItemDecoration;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.PayMethod;
import com.example.peibei.bean.SpUserInfoCall;
import com.example.peibei.service.presenter.PayBalancePresenter;
import com.example.peibei.service.presenter.PayOrderPresenter;
import com.example.peibei.service.presenter.PayPowerPresenter;
import com.example.peibei.service.presenter.SubmitOrderPresenter;
import com.example.peibei.service.presenter.UserInfoPresenter;
import com.example.peibei.ui.adapter.PayMethodAdapter;
import com.example.peibei.ui.adapter.RadioButtonAdapter;
import com.example.peibei.ui.adapter.RadioButtonTimeAdapter;
import com.example.peibei.ui.weight.CEditText;
import com.example.peibei.ui.weight.CenterDialog;
import com.example.peibei.ui.weight.SelectRequestPaidan;
import com.huantansheng.easyphotos.ui.dialog.LoadingDialog;
import com.linxiao.framework.dialog.BottomDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.SinglePicker;

public class SubmitOrderActivity extends WDActivity {
    @BindView(R.id.rv_radiobutton)
    RecyclerView rv_radiobutton;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_job)
    TextView tv_job;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.et_money)
    TextView et_money;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.rv_pay)
    RecyclerView rv_pay;
    @BindView(R.id.rv_time)
    RecyclerView rv_time;
    @BindView(R.id.l_hour)
    RelativeLayout l_hour;

    private SPUtils spUtils;
    private String token;
    private String publishOrderId;
    private List<SubmitOrder.TimeSeletorDTO> radiobuttons;
    private RadioButtonAdapter radioButtonAdapter;
    private RadioButtonTimeAdapter radioButtonTimeAdapter;
    private PayMethodAdapter payMethodAdapter;
    private String startTime;
    private int max;//最大时间
    private int choose;//已选时间
    private int effective;//有效时间
    String payType;
    private Date startDate;
    private Date endDate;
    private String chooseStartTime;
    private int price;
    private String orderId;
    private String consumeOrderId;
    private PayOrderPresenter payOrderPresenter;
    private String chooseWeek;
    private PayBalancePresenter payBalancePresenter;
    public static SubmitOrderActivity submitOrderActivity;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_submit_order;
    }

    @Override
    protected void initView() {
        submitOrderActivity = this;

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        publishOrderId = bundle.getString("publishOrderId");
        userId = bundle.getString("userId");
        unit = bundle.getString("unit");
        Log.i("answer", "用户id:" + userId);
        spUtils = new SPUtils(SubmitOrderActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);

        SubmitOrderPresenter submitOrderPresenter = new SubmitOrderPresenter(new OrderDetailCall());
        submitOrderPresenter.reqeust("Bearer " + token, publishOrderId);
        PayPowerPresenter presenter2 = new PayPowerPresenter(new PayPowerData());
        presenter2.reqeust("Bearer " + token);

        radiobuttons = new ArrayList<>();

        rv_radiobutton.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rv_radiobutton.addItemDecoration(new SpacingItemDecoration(30));
        radioButtonAdapter = new RadioButtonAdapter(radiobuttons, SubmitOrderActivity.this);
        rv_radiobutton.setAdapter(radioButtonAdapter);

        rv_time.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rv_time.addItemDecoration(new SpacingItemDecoration(30));
        radioButtonTimeAdapter = new RadioButtonTimeAdapter( SubmitOrderActivity.this);
        rv_time.setAdapter(radioButtonTimeAdapter);

        payMethodAdapter = new PayMethodAdapter();
        payMethodAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                PayPower item = payMethodAdapter.getItem(position);
                payType = item.getPayKey();
                payMethodAdapter.mSelectedItem = position;
                payMethodAdapter.notifyDataSetChanged();
            }
        });
        rv_pay.setAdapter(payMethodAdapter);
        rv_pay.setLayoutManager(new LinearLayoutManager(this));

        radioButtonAdapter.setOnItemClickListener(new RadioButtonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(SubmitOrder.TimeSeletorDTO data, int pos) {
                if (data.getStatus() == 1) {
                    resetDate(data,false);
                    chooseWeek = data.getTips();
                    radioButtonTimeAdapter.performClick();
                }
            }
        });
        radioButtonTimeAdapter.setOnItemClickListener(new RadioButtonTimeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String data, int pos) {
                try {
                    chooseStartTime = data;
                    Date date = DateUtils.dateParseHour(chooseStartTime, "yyyy-MM-dd HH:mm:ss");
                    effective = (int) (endDate.getTime() - date.getTime()) / (60 * 60 * 1000);

                    et_money.setText(effective + "");
                    if (!"-1".equals(unit)){
                        choose = effective;
                        tv_money.setText(effective * price + "");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
        if (TextUtils.equals("-1",unit)){
            l_hour.setVisibility(View.GONE);
        }
        if ("0".equals(unit)){
            tv_unit.setText("/小时");
        }else if ("1".equals(unit)){
            tv_unit.setText("/天");
        }else if("-1".equals(unit)){
            tv_unit.setText("￥一口价");
        }
        payOrderPresenter = new PayOrderPresenter(new PayOrderCall());
        payBalancePresenter = new PayBalancePresenter(new PayBanlanceCall());
    }

    private static final int SDK_PAY_FLAG = 1;

    class PayOrderCall implements DataCall<PayOrder> {

        @Override
        public void success(PayOrder data, Object... args) {
            if (TextUtils.equals("0",payType)) {
                if (data.getStatus().equals("0")) {
                    UIUtils.showToastSafe("您的余额不足，请充值");
                } else {
                    payOrderSure(data);
                }
            } else if (TextUtils.equals("2",payType)) {
                String retString = data.getRetString();
                payOrderForAlipay(retString);
            } else if (TextUtils.equals("1",payType)){
                payOrderForWx(data);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
//            UIUtils.showToastSafe(e.getDisplayMessage());
        }
    }

    public static final String APP_ID = "wx4de7acf350b321e9";

    private void payOrderForWx(PayOrder data) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        IWXAPI wxapi = WXAPIFactory.createWXAPI(this, APP_ID, true);

        // 将应用的appId注册到微信
        wxapi.registerApp(APP_ID);

        PayReq req = new PayReq();
        req.appId = data.getAppId();
        req.partnerId = data.getPartnerId();
        req.prepayId = data.getPrePayId();
        req.packageValue = data.get_package();
        req.nonceStr = data.getNonceStr();
        req.timeStamp = data.getTimestamp();
//        req.extData = extData;
        req.sign = data.getSign();

        // 调起微信支付页面
        boolean result = wxapi.sendReq(req);
    }

    private void payOrderForAlipay(String retString) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(SubmitOrderActivity.this);
                Map<String, String> result = alipay.payV2(retString, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                       newIntent();
//                        showAlert(SubmitOrderActivity.this, "支付成功" + payResult);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        UIUtils.showToastSafe(payResult.getMemo());
                    }
                    break;
                }
            }
        }
    };

    public void newIntent(){
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("支付中...");
        dialog.show();
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
                UIUtils.showToastSafe("支付成功");
                finish();
                Bundle bundle = new Bundle();
                bundle.putString("consumeOrderId", consumeOrderId);
                bundle.putString("userId", userId);
                bundle.putString("nickName", nickname);
                bundle.putInt("status", 0);
                intent(MyGetOrderDetailActivity.class, bundle);
            }
        },3000);
    }


    class PayBanlanceCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            newIntent();
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    private void payOrderSure(PayOrder data) {
        User loginUser = SpConstant.getLoginUser();
        if (TextUtils.equals("false",loginUser.getPayPwd())) {
            intent(SettingPayPswActivity.class);
        } else {
            showDialog(data);
        }
    }

    private void showDialog(PayOrder data) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_input_password, null);
//        BottomDialog bottomDialog = new BottomDialog(this);
        CenterDialog bottomDialog = new CenterDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog.show();
        ImageView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_money = dialogView.findViewById(R.id.tv_money);
        TextView tv_type = dialogView.findViewById(R.id.tv_type);
        CEditText cedittext = dialogView.findViewById(R.id.cedittext);
        tv_money.setText("￥" + data.getMoney());
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        cedittext.setOnFinishListener(msg -> {
            PayBanlance payBanlanceOrder = new PayBanlance();
            payBanlanceOrder.setOrderId(data.getOrderId());
            payBanlanceOrder.setPreId(data.getPreId());
            payBanlanceOrder.setType("0");
            payBanlanceOrder.setPayKey(msg);
            payBalancePresenter.reqeust("Bearer " + token, payBanlanceOrder);
        });
    }


    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.bt_pay)
    public void payOrder() {
//        if (!loginUser.isIdentityBool()) {
//            showBindAccount();
//            return;
//        }
        if (chooseWeek == null) {
            UIUtils.showToastSafe("请选择预定时间");
            return;
        }
        if (choose == 0){
            UIUtils.showToastSafe("请选择开始时间");
        }
        payOrderPresenter.reqeust("Bearer " + token, choose, chooseStartTime, orderId, payType + "", "");
    }

    @OnClick(R.id.rl_edit_money)
    public void reduceHour() {
        String trim = et_money.getText().toString().trim();
        int money = Integer.parseInt(trim);
        if (money > 1) {
            choose = money - 1;
            et_money.setText(String.valueOf(choose));
            tv_money.setText(choose * price + "");
        }
    }

    @OnClick(R.id.rl_edit_money_right)
    public void addHour() {
        if (choose == 0){
            return;
        }
        String trim = et_money.getText().toString().trim();
        int money = Integer.parseInt(trim);
        if (money < effective) {
            choose = money + 1;
            et_money.setText(String.valueOf(choose));
            tv_money.setText(choose * price + "");
        }
    }


    class OrderDetailCall implements DataCall<SubmitOrder> {

        @Override
        public void success(SubmitOrder data, Object... args) {
            setOrderDetail(data);
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    private void showBindAccount() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(SubmitOrderActivity.this);
        final View dialogView = LayoutInflater.from(SubmitOrderActivity.this)
                .inflate(R.layout.dialog_bind_account, null);
        normalDialog.setView(dialogView);
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_name = dialogView.findViewById(R.id.tv_name);
        TextView tv_sure = dialogView.findViewById(R.id.tv_sure);
        TextView tv_title = dialogView.findViewById(R.id.tv_title);
        tv_name.setText("提示");
        tv_title.setText("完成身份认证即可下单");
        tv_sure.setText("去认证");
        AlertDialog alertDialog = normalDialog.create();
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
                intent(RealNameActivity.class);
            }
        });
        // 显示
        alertDialog.show();
    }

    class  PayPowerData implements DataCall<List<PayPower>> {

        @Override
        public void success(List<PayPower> data, Object... args) {
            for (PayPower datum : data) {
                if (payType == null){
                    payType = datum.getPayKey();
                }
                if (datum.getStatus() == 1){
                    payMethodAdapter.addData(datum);
                }
            }
        }

        @Override
        public void fail(ApiException data, Object... args) {

        }
    }

    String nickname;
    String userId;
    String unit;

    private void setOrderDetail(SubmitOrder data) {
        unit = data.getUnit();
        if ("0".equals(data.getUnit())){
            tv_unit.setText("/小时");
        }else if ("1".equals(data.getUnit())){
            tv_unit.setText("/天");
        }else if("-1".equals(data.getUnit())){
            tv_unit.setText("￥一口价");
        }

        consumeOrderId = data.getId();
        Log.i("answer", "消费订单id:" + consumeOrderId);
        orderId = data.getId();
        nickname = data.getNickName();
        Log.i("answer", "用户昵称:" + nickname);
        tv_name.setText(data.getNickName());
        tv_job.setText(data.getCategory());
        tv_price.setText(data.getPrice());
        tv_money.setText(data.getPrice());
        price = (int) Math.ceil(Double.parseDouble(data.getPrice()));
        Glide.with(this).load(data.getImgUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
        radiobuttons.clear();
        radiobuttons.addAll(data.getTimeSeletor());
        radioButtonAdapter.notifyDataSetChanged();
        for (int i = 0; i < radiobuttons.size(); i++) {
            SubmitOrder.TimeSeletorDTO item = radiobuttons.get(i);
            if (item.getStatus() == 1) {
                resetDate(item,false);
                return;
            }
        }
        Log.i("answer", "-------:");
    }

    private void resetDate(SubmitOrder.TimeSeletorDTO data,boolean isAddHour) {
        try {
            if ("-1".equals(unit)){
                max = 24;
                choose = 1;
            }else {
                max = data.getMax();
            }

            effective = data.getMax();

            startTime = data.getRealDate();
            startDate = DateUtils.dateParseHour(startTime, "");
            endDate = DateUtils.dateAddHours(startDate, max);
            chooseStartTime = startTime;

            if (isAddHour)
            addHour();

            ArrayList<String> list = new ArrayList<>();
            list.add(startTime);
            for (int i = 0; i < max - 1; i++) {
                Date date = DateUtils.dateAddHours(startDate, i + 1);
                list.add(DateUtils.dateFormat(date, "yyyy-MM-dd HH:mm:ss"));
            }
            radioButtonTimeAdapter.setNewInstance(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void destoryData() {
        submitOrderActivity = null;
    }
}
